import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { addAddress, type AddAddressParams } from '../../api/addressApi'
import './addAddress.css'

/**
 * 添加收货地址组件
 */
function AddAddress() {
  // 使用useNavigate钩子进行页面导航
  const navigate = useNavigate()
  // 使用useState管理表单数据
  const [formData, setFormData] = useState({
    recipient: '',    // 收货人姓名
    phone: '',       // 手机号码
    region: '',      // 所在地区
    detailAddress: '' // 详细地址
  })
  // 是否设为默认地址
  const [isDefault, setIsDefault] = useState(false)
  // 控制地区选择器显示状态
  const [showRegionPicker, setShowRegionPicker] = useState(false)
  // 加载状态
  const [isLoading, setIsLoading] = useState(false)
  // 选中的地区数据
  const [selectedRegion, setSelectedRegion] = useState({
    province: '北京市',  // 省份
    city: '北京城区',   // 城市  // 区县
    district: '东城区'
  })

  // 地区数据
  const regionData = {
    provinces: ['北京市', '天津市', '河北省', '山西省', '内蒙古自治区'],
    cities: {
      '北京市': ['北京城区', '海淀区', '朝阳区', '丰台区', '石景山区'],
      '天津市': ['天津城区', '和平区', '河东区', '河西区', '南开区'],
      '河北省': ['石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市'],
      '山西省': ['太原市', '大同市', '阳泉市', '长治市', '晋城市'],
      '内蒙古自治区': ['呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市']
    },
    districts: {
      '北京城区': ['东城区', '西城区', '崇文区', '宣武区'],
      '海淀区': ['中关村', '学院路', '西二旗', '上地', '清河'],
      '朝阳区': ['三里屯', '国贸', '望京', '酒仙桥', '双井'],
      '丰台区': ['方庄', '右安门', '西罗园', '太平桥', '东铁匠营'],
      '石景山区': ['八宝山', '老山', '八角', '古城', '苹果园'],
      '天津城区': ['和平区', '河东区', '河西区', '南开区', '河北区'],
      '和平区': ['劝业场', '小白楼', '南市', '新兴', '体育馆'],
      '河东区': ['大王庄', '大直沽', '春华', '向阳楼', '常州道'],
      '河西区': ['大营门', '下瓦房', '桃园村', '挂甲寺', '马场'],
      '南开区': ['长虹', '鼓楼', '兴南', '广开', '万兴'],
      '石家庄市': ['长安区', '桥西区', '新华区', '井陉矿区', '裕华区'],
      '唐山市': ['路北区', '路南区', '古冶区', '开平区', '丰南区'],
      '秦皇岛市': ['海港区', '山海关区', '北戴河区', '抚宁区'],
      '邯郸市': ['邯山区', '丛台区', '复兴区', '峰峰矿区'],
      '邢台市': ['桥东区', '桥西区', '邢台县'],
      '太原市': ['小店区', '迎泽区', '杏花岭区', '尖草坪区'],
      '大同市': ['新荣区', '平城区', '云冈区', '云州区'],
      '阳泉市': ['城区', '矿区', '郊区'],
      '长治市': ['潞州区', '上党区', '屯留区', '潞城区'],
      '晋城市': ['城区', '沁水县', '阳城县', '陵川县'],
      '呼和浩特市': ['新城区', '回民区', '玉泉区', '赛罕区'],
      '包头市': ['东河区', '昆都仑区', '青山区', '石拐区'],
      '乌海市': ['海勃湾区', '海南区', '乌达区'],
      '赤峰市': ['红山区', '元宝山区', '松山区'],
      '通辽市': ['科尔沁区', '科尔沁左翼中旗', '科尔沁左翼后旗']
    }
  }

/**
 * 处理输入框内容变化的函数
 * @param field - 表单字段名称
 * @param value - 输入框的值
 */
  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
    // 更新对应字段的值
      [field]: value
    }))
  }

  const handleSave = async () => {
    // 表单验证
    if (!formData.recipient.trim()) {
      alert('请输入收货人姓名')
      return
    }
    if (!formData.phone.trim()) {
      alert('请输入手机号码')
      return
    }
    if (!formData.region.trim()) {
      alert('请选择所在地区')
      return
    }
    if (!formData.detailAddress.trim()) {
      alert('请输入详细地址')
      return
    }

    setIsLoading(true)

    try {
      // 调用新增收货地址API
      console.log('🚀 开始调用新增收货地址API...')
      
      const apiParams: AddAddressParams = {
        name: formData.recipient.trim(),
        phone: formData.phone.trim(),
        city: formData.region.trim(),
        desc: formData.detailAddress.trim(),
        state: isDefault ? 1 : 0  // 0: 非默认, 1: 默认
      }
      
      console.log('📝 API请求参数:', apiParams)
      
      const response = await addAddress(apiParams)
      
      console.log('✅ API响应:', response)
      
      // 检查API响应
      if (response.data && response.data.code === 20000) {
        // API调用成功
        console.log('✅ 新增收货地址成功')
        
        // 创建新地址对象用于本地存储
        const newAddress = {
          recipient: formData.recipient.trim(),
          phone: formData.phone.trim(),
          region: formData.region.trim(),
          detailAddress: formData.detailAddress.trim(),
          isDefault: isDefault
        }

        // 将新地址数据传递回地址列表页面
        navigate('/address', { 
          state: { newAddress } 
        })
      } else {
        // API返回错误
        const errorMsg = response.data?.message || '新增地址失败'
        console.error('❌ API返回错误:', errorMsg)
        alert(`新增地址失败: ${errorMsg}`)
      }
      
    } catch (error) {
      console.error('❌ API请求失败:', error)
      
      // API调用失败，使用本地存储作为备选方案
      console.log('⚠️ 使用本地存储作为备选方案')
      
      const newAddress = {
        recipient: formData.recipient.trim(),
        phone: formData.phone.trim(),
        region: formData.region.trim(),
        detailAddress: formData.detailAddress.trim(),
        isDefault: isDefault
      }

      // 将新地址数据传递回地址列表页面
      navigate('/address', { 
        state: { newAddress } 
      })
    } finally {
      setIsLoading(false)
    }
  }

/**
 * 处理地区选择按钮点击事件的函数
 * 当用户点击地区选择按钮时，会调用此函数来显示地区选择器
 */
  const handleRegionSelect = () => {
  // 设置地区选择器的显示状态为true，从而弹出地区选择界面
    setShowRegionPicker(true)
  }

  const handleRegionConfirm = () => {
    const regionText = `${selectedRegion.province} ${selectedRegion.city} ${selectedRegion.district}`
    setFormData(prev => ({
      ...prev,
      region: regionText
    }))
    setShowRegionPicker(false)
  }

  const handleRegionCancel = () => {
    setShowRegionPicker(false)
  }

  const handleRegionItemClick = (type: 'province' | 'city' | 'district', value: string) => {
    setSelectedRegion(prev => {
      const newRegion = { ...prev }
      
      if (type === 'province') {
        newRegion.province = value
        // 重置城市和区县
        const cities = regionData.cities[value as keyof typeof regionData.cities]
        newRegion.city = cities?.[0] || ''
        const districts = regionData.districts[newRegion.city as keyof typeof regionData.districts]
        newRegion.district = districts?.[0] || ''
      } else if (type === 'city') {
        newRegion.city = value
        // 重置区县
        const districts = regionData.districts[value as keyof typeof regionData.districts]
        newRegion.district = districts?.[0] || ''
      } else if (type === 'district') {
        newRegion.district = value
      }
      
      return newRegion
    })
  }

  return (
    <div className="add-address-page">
      {/* 顶部导航栏 */}
      <div className="add-address-header">
        <button className="back-btn" onClick={() => navigate(-1)}>
          ←
        </button>
        <div className="header-title">收货地址-添加</div>
        <div className="header-actions">
          <button className="action-btn">⋯</button>
          <button className="action-btn">-</button>
          <button className="action-btn">◎</button>
        </div>
      </div>

      {/* 表单区域 */}
      <div className="form-section">
        <div className="form-item">
          <label className="form-label">收货人:</label>
          <input
            type="text"
            className="form-input"
            placeholder="请输入姓名"
            value={formData.recipient}
            onChange={(e) => handleInputChange('recipient', e.target.value)}
          />
        </div>

        <div className="form-item">
          <label className="form-label">手机号码:</label>
          <input
            type="tel"
            className="form-input"
            placeholder="请输入手机号码"
            value={formData.phone}
            onChange={(e) => handleInputChange('phone', e.target.value)}
          />
        </div>

                 <div className="form-item">
           <label className="form-label">所在地区:</label>
           <div className="region-selector" onClick={handleRegionSelect}>
             <span className={formData.region ? 'region-text' : 'region-placeholder'}>
               {formData.region || '请选择所在地'}
             </span>
             <span className="arrow-icon">{'>'}</span>
           </div>
         </div>

        <div className="form-item">
          <label className="form-label">详细地址:</label>
          <input
            type="text"
            className="form-input"
            placeholder="街道门牌,无需重复地区信息"
            value={formData.detailAddress}
            onChange={(e) => handleInputChange('detailAddress', e.target.value)}
          />
        </div>
      </div>

      {/* 默认地址设置 */}
      <div className="default-section">
        <div className="default-content">
          <div className="default-info">
            <div className="default-title">设为默认</div>
            <div className="default-desc">每次购买时会默认使用该地址</div>
          </div>
          <div className="toggle-switch" onClick={() => setIsDefault(!isDefault)}>
            <div className={`toggle-slider ${isDefault ? 'active' : ''}`}></div>
          </div>
        </div>
      </div>

                     {/* 底部保存按钮 */}
        <div className="bottom-action">
          <button className="save-btn" onClick={handleSave} disabled={isLoading}>
            {isLoading ? '保存中...' : '保存'}
          </button>
        </div>

        {/* 地区选择弹窗 */}
        {showRegionPicker && (
          <div className="region-picker-overlay" onClick={handleRegionCancel}>
            <div className="region-picker-modal" onClick={(e) => e.stopPropagation()}>
              {/* 弹窗头部 */}
              <div className="picker-header">
                <button className="picker-btn cancel-btn" onClick={handleRegionCancel}>
                  取消
                </button>
                <div className="picker-title">地区选择</div>
                <button className="picker-btn confirm-btn" onClick={handleRegionConfirm}>
                  确认
                </button>
              </div>
              
              {/* 地区选择器 */}
              <div className="region-picker-content">
                <div className="picker-column">
                  {regionData.provinces.map(province => (
                    <div
                      key={province}
                      className={`picker-item ${selectedRegion.province === province ? 'active' : ''}`}
                      onClick={() => handleRegionItemClick('province', province)}
                    >
                      {province}
                    </div>
                  ))}
                </div>
                <div className="picker-column">
                  {regionData.cities[selectedRegion.province as keyof typeof regionData.cities]?.map(city => (
                    <div
                      key={city}
                      className={`picker-item ${selectedRegion.city === city ? 'active' : ''}`}
                      onClick={() => handleRegionItemClick('city', city)}
                    >
                      {city}
                    </div>
                  ))}
                </div>
                <div className="picker-column">
                  {regionData.districts[selectedRegion.city as keyof typeof regionData.districts]?.map(district => (
                    <div
                      key={district}
                      className={`picker-item ${selectedRegion.district === district ? 'active' : ''}`}
                      onClick={() => handleRegionItemClick('district', district)}
                    >
                      {district}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    )
  }

export default AddAddress
